<template>
  <div class="login-container">
    <div class="login-form-wrapper">
      <div class="login-title">
        <h2>管理后台登录</h2>
        <p>请输入您的账号和密码</p>
      </div>
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-width="0px"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
            clearable
            autocomplete="on"
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        <el-form-item prop="captcha" v-if="showCaptcha">
          <div class="captcha-container">
            <el-input
              v-model="loginForm.captcha"
              placeholder="请输入验证码"
              prefix-icon="Check"
              @keyup.enter="handleLogin"
            />
            <div class="captcha-image" @click="refreshCaptcha">
              <img :src="captchaUrl" alt="验证码" />
            </div>
          </div>
        </el-form-item>
        <el-form-item class="login-options">
          <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
          <el-link type="primary" @click="handleForgotPassword" class="forgot-password">忘记密码?</el-link>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="login-btn"
            :loading="loading"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  name: 'Login',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const loginFormRef = ref(null)
    const loading = ref(false)
    const showCaptcha = ref(false)
    const captchaUrl = ref('')
    
    const loginForm = reactive({
      username: '',
      password: '',
      captcha: '',
      remember: false
    })
    
    const loginRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      captcha: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { min: 4, max: 6, message: '验证码长度错误', trigger: 'blur' }
      ]
    }
    
    // 刷新验证码
    const refreshCaptcha = () => {
      // 生成时间戳避免缓存
      const timestamp = new Date().getTime()
      captchaUrl.value = `/api/captcha?timestamp=${timestamp}`
    }
    
    // 处理登录
    const handleLogin = async () => {
      try {
        // 表单验证
        await loginFormRef.value.validate()
        
        loading.value = true
        
        // 调用登录接口
        const response = await axios.post('/api/users/login', {
          name: loginForm.username,
          password: loginForm.password
        })
        
        // 处理响应 - 考虑axios拦截器的影响
        if (response.code === 200) {
            // 保存token到localStorage
            const token = response.data
            
            localStorage.setItem('token', token)
            
            // 保存用户基本信息到localStorage（由于后端只返回token，我们使用用户名作为用户信息）
            const userInfo = {
                name: loginForm.username,
                avatar: ''
            }
            localStorage.setItem('userInfo', JSON.stringify(userInfo))
            
            // 调用接口获取用户权限
            try {
              const permissionResponse = await axios.get('/api/permission/current-user')
              if (permissionResponse.code === 200 && permissionResponse.data) {
                // 从返回的权限列表中提取权限代码
                const permissions = permissionResponse.data.map(perm => perm.code || perm)
                localStorage.setItem('permissions', JSON.stringify(permissions))
              } else {
                // 如果获取失败，使用默认权限
                localStorage.setItem('permissions', JSON.stringify(['admin']))
              }
            } catch (error) {
              console.error('获取用户权限失败:', error)
              // 出错时使用默认权限
              localStorage.setItem('permissions', JSON.stringify(['admin']))
            }
            
            // 如果有记住我选项，可以将用户信息保存到localStorage
            if (loginForm.remember) {
                localStorage.setItem('rememberedUsername', loginForm.username)
            } else {
                localStorage.removeItem('rememberedUsername')
            }
            
            // 跳转到登录前的页面或首页
            const redirect = route.query.redirect || '/dashboard'
            router.push(redirect)
        } else if (response.token) {
            // 如果直接返回了token（拦截器生效）
            localStorage.setItem('token', response.token)
            
            // 保存用户基本信息到localStorage
            const userInfo = {
                name: loginForm.username,
                avatar: ''
            }
            localStorage.setItem('userInfo', JSON.stringify(userInfo))
            
            // 调用接口获取用户权限
            try {
              const permissionResponse = await axios.get('/api/permission/current-user')
              if (permissionResponse.code === 200 && permissionResponse.data) {
                // 从返回的权限列表中提取权限代码
                const permissions = permissionResponse.data.map(perm => perm.code || perm)
                localStorage.setItem('permissions', JSON.stringify(permissions))
              } else {
                // 如果获取失败，使用默认权限
                localStorage.setItem('permissions', JSON.stringify(['admin']))
              }
            } catch (error) {
              console.error('获取用户权限失败:', error)
              // 出错时使用默认权限
              localStorage.setItem('permissions', JSON.stringify(['admin']))
            }
            
            // 如果有记住我选项，可以将用户信息保存到localStorage
            if (loginForm.remember) {
                localStorage.setItem('rememberedUsername', loginForm.username)
            } else {
                localStorage.removeItem('rememberedUsername')
            }
            
            // 跳转到登录前的页面或首页
            const redirect = route.query.redirect || '/dashboard'
            router.push(redirect)
        } else if (response.code === 401) {
            // 用户名或密码错误
            ElMessage.error(response.message || '用户名或密码错误')
            
            // 如果连续失败，显示验证码
            if (!showCaptcha.value) {
                showCaptcha.value = true
                refreshCaptcha()
            }
        } else {
            // 其他错误
            ElMessage.error(response.message || '登录失败，请重试')
        }
      } catch (error) {
        console.error('登录错误:', error)
        ElMessage.error('登录失败，请检查网络连接或稍后重试')
      } finally {
        loading.value = false
      }
    }
    
    // 处理忘记密码
    const handleForgotPassword = () => {
      // 跳转到忘记密码页面或显示提示
      ElMessage.info('请联系管理员重置密码')
    }
    
    onMounted(() => {
      // 从localStorage获取记住的用户名
      const rememberedUsername = localStorage.getItem('rememberedUsername')
      if (rememberedUsername) {
        loginForm.username = rememberedUsername
        loginForm.remember = true
      }
      
      // 默认情况下不显示验证码，只有登录失败次数达到一定阈值才显示
      // 这里可以根据实际需求调整
    })
    
    return {
      loginFormRef,
      loginForm,
      loginRules,
      loading,
      showCaptcha,
      captchaUrl,
      handleLogin,
      handleForgotPassword,
      refreshCaptcha
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  background-size: 100% 100%;
  position: relative;
  overflow: hidden;
}

/* 背景装饰 */
.login-container::before {
  content: '';
  position: absolute;
  width: 300px;
  height: 300px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  top: -150px;
  right: -150px;
}

.login-container::after {
  content: '';
  position: absolute;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.05);
  bottom: -100px;
  left: -100px;
}

.login-form-wrapper {
  background: white;
  padding: 40px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
  position: relative;
  z-index: 1;
  backdrop-filter: blur(10px);
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
}

.login-title h2 {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.login-title p {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.login-form {
  width: 100%;
}

.login-form .el-form-item {
  margin-bottom: 20px;
}

.login-form .el-input {
  height: 40px;
}

.login-form .el-input__wrapper {
  border-radius: 8px;
}

.captcha-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

.captcha-image {
  width: 120px;
  height: 40px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.captcha-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.forgot-password {
  font-size: 12px;
}

.login-btn {
  width: 100%;
  height: 40px;
  font-size: 16px;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  transition: all 0.3s ease;
}

.login-btn:hover {
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.login-btn:active {
  transform: translateY(0);
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-form-wrapper {
    padding: 30px 20px;
    margin: 0 20px;
  }
  
  .captcha-container {
    flex-direction: column;
    align-items: stretch;
  }
  
  .captcha-image {
    width: 100%;
    height: 40px;
  }
}
</style>